﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.ServiceProcess;
using BackupLibrary;
using System.Data;
using System.Diagnostics;
using System.Text;

namespace BackupService
{
    partial class SqlBackupService : ServiceBase
    {
        Queue<Job> _allTask = new Queue<Job>();
        System.Timers.Timer Timer1 = new System.Timers.Timer(1000);

        Jobs _allJobs = null;

        public SqlBackupService()
        {
            InitializeComponent();
            Timer1.Enabled = false;
            Timer1.Elapsed += new System.Timers.ElapsedEventHandler(Timer1_Elapsed);
        }

        void Timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            foreach (Job item in _allJobs.AllTask)
            {
                if (item.StartingDate.Hour == DateTime.Now.Hour && item.StartingDate.Minute == DateTime.Now.Minute && item.StartingDate.Second == DateTime.Now.Second)
                {
                    _allTask.Enqueue(item);
                }
            }

            if (!backgroundWorker1.IsBusy && _allTask.Count > 0)
            {
                Timer1.Stop();
                Timer1.Enabled = false;
                backgroundWorker1.WorkerSupportsCancellation = true;
                backgroundWorker1.RunWorkerAsync(_allTask.Dequeue());
            }
        }



        protected override void OnStart(string[] args)
        {
            String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
            path = System.IO.Path.GetDirectoryName(path);

            if (File.Exists(path + "\\Jobs.xml"))
            {
                _allJobs = new Serialization().DeserializeJob(File.ReadAllText(path + "\\Jobs.xml"));
                if (_allJobs.AllTask.Count > 0)
                {
                    Timer1.Enabled = true;
                    Timer1.Start();
                }
            }
        }

        protected override void OnStop()
        {
            Timer1.Stop();
            Timer1.Enabled = false;
            Settings.Get.SaveAll();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (e.Argument != null)
            {
                Job job = e.Argument as Job;
                if (!BackupProcess.BackupNow(job))
                {
                    _allTask.Enqueue(job);
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Timer1.Enabled = true;
            Timer1.Start();
        }
    }
}
